package com.campus.customer.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.customer.vo.UserInfoVo;
import com.campus.customer.bean.user.UserBean;
import com.campus.customer.entity.User;
import com.campus.customer.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author ZhaoYuJie
 * @since 2025-04-02
 */
@Service
public class UserService extends ServiceImpl<UserMapper, User> {
    @Autowired
    private SessionService sessionService;
    @Autowired
    private RedisService redisService;

    @Transactional(rollbackFor = Exception.class)
    public void updateUserInfo(Integer id, UserBean userBean) {
        User user = new User();
        user.setId(id);
        user.setNickname(userBean.getNickname());
        user.setAvatar(userBean.getAvatar());
        user.setPhone(userBean.getPhone());
        this.updateById(user);

        updateUserInfoToRedis(id);
    }

    /**
     * 更新用户信息到redis
     * @param userId
     */
    public void updateUserInfoToRedis(Integer userId) {
        User user = this.getById(userId);
        UserInfoVo userInfoVo = sessionService.getUserInfo();
        BeanUtils.copyProperties(user, userInfoVo);
        redisService.setWithoutChangingTtl(sessionService.getToken(), JSON.toJSONString(userInfoVo));
    }
}
